<!-- 页面  -->
<template>
	<view>
		<view class="ss-flex flex-wrap">
			<view class="goods-box" v-for="item in pagination?.data" :key="item.id">
				<view>
					<view class="goods-img" @click="handleGoodsClick(item)">
						<image class="goods-img" :src="sheep.$url.cdn(item.image)" mode="aspectFit"></image>
					</view>
					<view class="goods-content">
						<view class="goods-title ss-line-1 ss-m-b-28">{{ item.title }}</view>
						<view class="flex-center">
							<view class="price-container">
								<!-- 共富会员：显示会员价和原价（original_price） -->
								<view v-if="state.userInfo && state.userInfo.level == 2" class="goods-price">
									￥{{ item.vip_price || (item.price ? item.price[0] : '暂无价格') }}
								</view>
								<view v-if="state.userInfo && state.userInfo.level == 2 && item.vip_price && item.original_price" class="original-price">
									￥{{ item.original_price }}
								</view>
								
								<!-- 优惠会员：显示会员价和原价（original_price） -->
								<view v-if="state.userInfo && state.userInfo.level == 1" class="goods-price">
									￥{{ item.vip_price || (item.price ? item.price[0] : '暂无价格') }}
								</view>
								<view v-if="state.userInfo && state.userInfo.level == 1 && item.vip_price && item.original_price" class="original-price">
									￥{{ item.original_price }}
								</view>
								
								<!-- 注册会员：只显示一个价格 -->
								<view v-if="!state.userInfo || state.userInfo.level == 0" class="goods-price">
									￥{{ item.price ? item.price[0] : '暂无价格' }}
								</view>
							</view>
							<view class="title-flex" @click="handleAdd(item.id)">
								<image mode="widthFix" class="add-img" :src="state.addShop"></image>
								<view class="tui-scale-collection">加购</view>
							</view>
						</view>
					</view>

				</view>

			</view>

			


		</view>
	</view>
</template>

<script setup>
	import { reactive, computed, onMounted } from 'vue';
	import { onLoad, onPageScroll, onShareAppMessage } from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import { formatSales, formatGoodsSwiper, formatPrice } from '@/sheep/hooks/useGoods';
	import detailCellSku from './detail/detail-cell-sku.vue';
	import detailCellService from './detail/detail-cell-service.vue';
	import detailCellParams from './detail/detail-cell-params.vue';
	import detailTabbar from './detail/detail-tabbar.vue';
	import detailSkeleton from './detail/detail-skeleton.vue';
	import detailCommentCard from './detail/detail-comment-card.vue';
	import detailContentCard from './detail/detail-content-card.vue';
	import detailActivityTip from './detail/detail-activity-tip.vue';
	import { isEmpty } from 'lodash';
	const state = reactive({
		goodsId: 0,
		skeletonLoading: true,
		goodsInfo: {},
		showSelectSku: false,
		goodsSwiper: [],
		selectedSkuPrice: {},
		showModel: false,
		total: 0,
		couponInfo: [],
		showActivityModel: false,
		activityInfo: [],
		addShop: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/addshop.png',
		gift: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/gift.png',
		goldenBean: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/goldenBean.png',
		downloadIcon: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/downloadIcon.png',
		shareIcon: 'https://wemayshiguang.oss-cn-shanghai.aliyuncs.com/shareIcon.png',
		isGift: '0',
		userInfo: {}
	})
	const props = defineProps({
		data: {
			type: Object,
			default: () => ({}),
		},
		activeMenu: [Number, String],
		pagination: Object,
	});

	const emit = defineEmits(['goodsClick', 'showAddCart']);

	// 获取用户信息
	const getUserInfo = async () => {
		try {
			const isLogin = sheep.$store('user').isLogin;
			if (isLogin) {
				const userInfo = await sheep.$store('user').getInfo();
				state.userInfo = userInfo || {};
			} else {
				state.userInfo = {
					level: 0,
					level_text: '普通用户'
				};
			}
		} catch (error) {
			console.error('获取用户信息失败:', error);
			state.userInfo = {
				level: 0,
				level_text: '普通用户'
			};
		}
	};

	const handleGoodsClick = (item) => {
		emit('goodsClick', item);
	}

	// 页面加载时获取用户信息
	onMounted(() => {
		getUserInfo();
	});;

	// 规格变更
	function onSkuChange(e) {
		state.selectedSkuPrice = e;
	}

	// 添加购物车
	function onAddCart(e) {
		// 检查登录状态
		const isLogin = sheep.$store('user').isLogin;
		if (!isLogin) {
			uni.showModal({
				title: '温馨提示',
				content: '添加购物车请先登录',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			return
		}
		sheep.$store('cart').add(e);
	}

	// 立即购买
	function onBuy(e) {
		// 检查登录状态
		const isLogin = sheep.$store('user').isLogin;
		if (!isLogin) {
			uni.showModal({
				title: '温馨提示',
				content: '添加购物车请先登录',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			return
		}

		if (state.isGift == '0') {
			sheep.$router.go('/subPackages/order/confirm', {
				data: JSON.stringify({
					order_type: 'goods',
					is_gift: '0',
					goods_list: [{
						goods_id: e.goods_id,
						goods_num: e.goods_num,
						goods_sku_price_id: e.id,
					}, ],
				}),
			});
		} else {
			sheep.$router.go('/subPackages/friendProductDetails/friendProductDetails', {
				data: JSON.stringify({
					order_type: 'goods',
					is_gift: '1',
					goods_list: [{
						goods_id: e.goods_id,
						goods_num: e.goods_num,
						goods_sku_price_id: e.id,
					}, ],
				}),
			});
		}

	}
	//营销活动
	function onActivity() {
		state.activityInfo = state.goodsInfo.promos;
		state.showActivityModel = true;
	}

	//立即领取
	async function onGet(id) {
		const { code, msg } = await sheep.$api.coupon.get(id);
		if (code === 1) {
			uni.showToast({
				title: msg,
			});
			setTimeout(() => {
				getCoupon();
			}, 1000);
		}
	}
	async function getCoupon(page = 1, list_rows = 5) {
		state.loadStatus = 'loading';
		let res = await sheep.$api.coupon.userCoupon({
			type: state.type,
			list_rows,
			page,
		});
		if (res.code === 1) {
			let couponlist = _.concat(state.pagination.data, res.data.data);
			state.pagination = {
				...res.data,
				data: couponlist,
			};
			if (state.pagination.current_page < state.pagination.last_page) {
				state.loadStatus = 'more';
			} else {
				state.loadStatus = 'noMore';
			}
		}
	}

	const shareInfo = computed(() => {
		if (isEmpty(state.goodsInfo)) return {};
		return sheep.$platform.share.getShareInfo({
			title: state.goodsInfo.title,
			image: sheep.$url.cdn(state.goodsInfo.image),
			desc: state.goodsInfo.subtitle,
			params: {
				page: '2',
				query: state.goodsInfo.id,
			},
		}, {
			type: 'goods', // 商品海报
			title: state.goodsInfo.title, // 商品标题
			image: sheep.$url.cdn(state.goodsInfo.image), // 商品主图
			price: state.goodsInfo.price[0], // 商品价格
			original_price: state.goodsInfo.original_price, // 商品原价
		}, );
	});


	const handleAdd = async (id) => {
		// 检查登录状态
		const isLogin = sheep.$store('user').isLogin;
		if (!isLogin) {
			uni.showModal({
				title: '温馨提示',
				content: '添加购物车请先登录',
				confirmText: '去登录',
				cancelText: '取消',
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/subPackages/login/login'
						})
					}
				}
			})
			return
		}

		try {
			// 获取商品详情
			const res = await sheep.$api.goods.detail(id);
			if (res.code === 1) {
				// 向父组件发送显示SKU弹框事件
				emit('showAddCart', {
					goodsInfo: res.data,
					goodsId: id,
					isGift: 0
				});
			} else {
				uni.showToast({
					title: res.msg || '获取商品信息失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('获取商品详情失败:', error);
			uni.showToast({
				title: '网络异常，请重试',
				icon: 'none'
			});
		}
	}
</script>

<style lang="scss" scoped>
	.title-flex {
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.tui-scale-collection {
		transform: scale(0.7);
		transform-origin: center 90%;
		line-height: 24rpx;
		font-weight: normal;
		color: #666666;
		margin-top: 4rpx;
		white-space: nowrap;
	}
	.flex-center{
		display: flex;
		justify-content:space-between;
		align-items:center;
	}

	.add-img {
		width: 40rpx;
		height: 40rpx;
	}

	.goods-box {
		width: calc((100% - 20rpx) / 2);
		margin-bottom: 20rpx;

		.goods-img {
			width: 100%;
			height: 246rpx;
			border-radius: 10rpx 10rpx 0px 0px;
		}

		.goods-content {
			width: 100%;
			background: #ffffff;
			box-shadow: 0px 0px 20rpx 4rpx rgba(199, 199, 199, 0.22);
			padding: 20rpx 0 32rpx 16rpx;
			box-sizing: border-box;
			border-radius: 0 0 10rpx 10rpx;

			.goods-title {
				font-size: 26rpx;
				font-weight: bold;
				color: #333333;
			}

			.price-container {
				display: flex;
				flex-direction: column;
				gap: 8rpx;
			}

			.goods-price {
				font-size: 24rpx;
				font-family: OPPOSANS;
				font-weight: 500;
				color: #FF7C00;
			}

			.original-price {
				font-size: 20rpx;
				font-family: OPPOSANS;
				font-weight: 400;
				color: #999999;
				text-decoration: line-through;
			}
		}

		&:nth-child(2n + 1) {
			margin-right: 20rpx;
		}
	}
</style>